package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckItemService;
import org.aspectj.bridge.Message;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/checkitem")
public class CheckItemController {

    @Reference
    public CheckItemService checkItemService;

    /**
     * 新增检测项
     * @param checkItem
     * @return
     */
    @PostMapping("/add")
    public Result insert(@RequestBody CheckItem checkItem) {
        //参数校验
        if(checkItem == null || StringUtils.isEmpty(checkItem.getName())
                || StringUtils.isEmpty(checkItem.getCode())){
            return new Result(false, MessageConstant.ADD_CHECKITEM_FAIL);
        }
        try {
            Integer result = checkItemService.insert(checkItem);
            if (result == 1) {
                return new Result(true, "新增成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, "新增失败");
    }

    /**
     * 删除检测项
     * @param id
     * @return
     */
    @GetMapping("/delete")
    public Result delete(Integer id){
        try {
            Integer result = checkItemService.delete(id);
            if(result == 1){
                return new Result(true,"删除成功");
            }else if(result == -1){
                return new Result(false,"检查项被检查组绑定，无法删除！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false,"删除失败");
    }

    @GetMapping("/findById")
    public Result findById(Integer id){
        CheckItem checkItem = checkItemService.findById(id);
        if(checkItem != null){
            return new Result(true,null,checkItem);
        }
        return new Result(false,"查询出错");
    }

    @PostMapping("/edit")
    public Result update(@RequestBody CheckItem checkItem) {
        Integer result = checkItemService.update(checkItem);
        if (result == 1) {
            return new Result(true, "更新成功");
        }
        return new Result(false, "更新失败");
    }

    @PostMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        return checkItemService.findList(queryPageBean);
    }

    @GetMapping("/findAll")
    public Result findAll(){
        List<CheckItem> all = checkItemService.findAll();
        if (all.isEmpty()){
            return new Result(false,"查询出错");
        }
        return new Result(true,null,all);
    }


}
